var roleManage = function() {

    var _init = function() {

        // 表单验证
        function validate(value, type) {
            // 字段值
            var value = $.trim(value);

            // 非空验证
            if (type === 'require') {
                return !!value;
            }
            // 手机号验证
            if (type === 'phone') {
                return /^1\d{10}$/.test(value);
            }
            // 邮箱验证
            if (type === 'email') {
                return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
            }
        }

        // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .help-block').html(''); // 清空提示
            // $('.modal input').val(''); // 清空 input
        });

        $('input[name=input_name]').on('keyup', function(){
            var value = $(this).val();
            if(value.length > 40){
                layer.msg('店铺名称最多为40个字符');
                return false;
            }
        });

        // 确定添加
        $('#modal_sure_new').click(function() {
            var _data = $("#tenant_form").serializeObject();

            var name = $('#modal_new_role [name="input_name"]').val();
            var contact_name = $('#modal_new_role [name="contact_name"]').val();
            var openWeek = _data.openWeek + "";

            var phone = $('#modal_new_role [name="input_phone"]').val();
            var openTime = $('#modal_new_role [name="input_openTime"]').val();
            var closeTime = $('#modal_new_role [name="input_closeTime"]').val();
            var address = $('#modal_new_role [name="input_address"]').val();
            var detailed_address = $('#modal_new_role [name="detailed_address"]').val();
            var province = $('#modal_new_role [name="province"]').val();
            var city = $('#modal_new_role [name="city"]').val();
            var district = $('#modal_new_role [name="district"]').val();
            var addressGeo = $('#modal_new_role [name="addressGeo"]').val();
            var id = $('#modal_new_role [name="id"]').val();

            var newDate = timeParse(openTime);
            var newDate1 = timeParse(closeTime);
            if (!validate(name, 'require')) {
                layer.msg('请填写店铺名称');
                return;
            }
            if (name.length > 40) {
                layer.msg('店铺名称最多为40个字符');
                return;
            }

            if (!validate(contact_name, 'require')) {
                layer.msg('请填写联系人姓名');
                return;
            }
            if (contact_name.length > 40) {
                layer.msg('联系人姓名最多为40个字符');
                return;
            }

            if (!validate(province, 'require')) {
                layer.msg('请选择省份');
                return;
            }
            if (!validate(city, 'require')) {
                layer.msg('请选择城市');
                return;
            }
            if (!validate(district, 'require')) {
                layer.msg('请选择区');
                return;
            }
            if (!validate(address, 'require')) {
                layer.msg('请填写定位地址');
                return;
            }
            if (address.length > 40) {
                layer.msg('详细地址最多为40个字符');
                return;
            }
            if(!validate(addressGeo, 'require')){
                layer.msg('此定位地址不能被百度地图标记');
                $('#modal_new_role [name="input_address"]').focus();
                return;
            }
            if (!_data.openWeek) {
                layer.msg('请选择营业天');
                return;
            }
            if (!validate(openTime, 'require')) {
                layer.msg('请选择营业开始时间');
                return;
            }
            if (!validate(closeTime, 'require')) {
                layer.msg('请选择营业结束时间');
                return;
            }
            if(closeTime <= openTime){
                layer.msg('营业开始时间不可大于结束时间');
                return;
            }
            if (!validate(phone, 'require')) {
                layer.msg('请填写电话');
                return;
            }
            // if (!validate(phone, 'phone')) {
            //     layer.msg('电话格式不正确');
            //     return;
            // }

            var _image = $("#storeImg").serializeObject();
            //console.log(_image);
            var imageId = _image.imageId;
            if(imageId == undefined) {
                layer.msg('请添加门店图片');
                return;
            }
            if(imageId instanceof Array){   //处理图片数组
                var length=imageId.length;
                array = new Array(length);
                for(var i=0;i<length;i++){
                    simg={"imageId":_image.imageId[i],"imageUrl":_image.imageUrl[i]};
                    array[i] = simg;
                }
            } else {
                array = new Array(1);
                array[0] = imageId.length == 0 ?  new Array() : _image;
            }

            if(parseInt(length)>9){
                layer.msg("店铺图片最多只能添加9张!");
                return;
            }
            if(parseInt(length)==0){
                layer.msg('请添加门店图片');
                return;
            }else {
                var param = {"store":{
                        "name" : name,
                        "openWeek" : _data.openWeek + "",
                        "phone" : phone,
                        "openTime" : openTime,
                        "address" : address,
                        "detailed_address" : detailed_address,
                        "closeTime" : closeTime,
                        "province" : province,
                        "city" : city,
                        "id" : id,
                        "addressGeo" : addressGeo,
                        "district" : district,
                        "contact_name":contact_name,
                        "storeImg":JSON.stringify(array)
                    }
                };

                //为避免多次重复提交，保存后先禁用，完成后启用
                $("#modal_sure_new").attr("disabled","disabled");
                var _type = id == null || id == '' ? "put": "post";
                var posturl = id == null || id == '' ? add_url : edit_url;
                $.ajax({
                    url : posturl,
                    type : _type,
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    if (data.status == 1) {
                        layer.msg('开店成功', {icon: 6, time: 3000});
                        window.location.href= index_url;
                        //加载页面数据

                    }else if(data.status == 41002){
                        //余额不足
                        layer.msg('余额不足，请充值', {icon: 5, time: 3000});
                        window.location.href= tenantrecharge_url;
                    }else if(data.status == 41009){
                        layer.msg(data.message, {icon: 5, time: 3000});
                        return false;
                    }
                    else if (data.status == '0') {
                        // 错误
                        $("#modal_sure_new").removeAttr("disabled");
                        layer.msg(data.message); // 返回错误信息
                    }
                });
            }
        });

    };

    return {
        init : function() {
            _init();
        }

    };

}();

// 获取时间
$(".data input[type='checkbox']").each(function() {
    if ($(this).is(":checked")) {
        $(this).parent("label").addClass("active");
    }
});
$(".data label").click(function() {
    if ($(this).is(".active")) {
        $(this).removeClass("active");
        $(this).find("input[type='checkbox']").prop("checked", false);
        return false;
    } else {
        $(this).addClass("active");
        $(this).find("input[type='checkbox']").prop("checked", true);
        return false;
    }
});

/*$("#add-text").change(function() {
	$("#add-text1").val("");
	$("#add-text1").attr("value", "");
});

$("#distpicker select").change(function() {
	$("#add-text1").val("");
	$("#add-text1").attr("value", "");
});*/
// 百度地图API功能
//创建Map实例
var map = new BMap.Map("map_container");
//初始化广州坐标
var point = new BMap.Point(114.405492,30.502934);
//地图平移缩放控件：默认左上方
map.addControl(new BMap.NavigationControl());
//比例尺控件，默认位于地图左下方，显示地图的比例关系
map.addControl(new BMap.ScaleControl());
map.centerAndZoom(point,12);
//添加鼠标滚动缩放
map.enableScrollWheelZoom(true);
//设置标注的图标
//var icon = new BMap.Icon("img/icon.jpg",new BMap.Size(100,100));
//设置标注的经纬度
var marker = new BMap.Marker(point);
//把标注添加到地图上
map.addOverlay(marker);

//地址解析类
var gc = new BMap.Geocoder();
//显示地址信息窗口
function showLocationInfo(pt, rs){
    var addComp = rs.addressComponents;
    $("#longitude").val(pt.lng);
    $("#latitude").val(pt.lat);
    console.log('经纬度：'+pt.lat+' '+pt.lng);
    $("#add-text1").val(pt.lat+','+pt.lng);
}

//删除标注
function deletePoint(){
    var allOverlay = map.getOverlays();
    for (var i = 0; i < allOverlay.length; i++){
        map.removeOverlay(allOverlay[i]);
    }
}

//根据选择框或输入框获取地址
var _area={
    //keyword:'',
    _areaLists:$(".areaLists"),
    _address:$("#address"),
    unChecked:function(val){
        return (val==''||typeof (val)=='undefined'||val==null||
            val=='省份'||val=='地级市'||val=='市、县级市')?false:true;
    },
    list:function(){
        var _joinArea='';
        for(var i=0;i<this._areaLists.length;i++){
            if(_area.unChecked(this._areaLists[i].value)){
                _joinArea+=this._areaLists[i].value;
            }
        }
        if(_area.unChecked(this._address.val())){
            _joinArea+=' '+this._address.val();
            //_joinArea=this._address.val();
        }
        return _joinArea;
    },
    init:function(){
        //绑定百度地图
        var _this=_area.list();
        //定义local
        var local = new BMap.LocalSearch(map, {
            renderOptions: {
                map: map,
                panel: "results",//结果容器id
                autoViewport: true,   //自动结果标注
                selectFirstResult: true  , //指定到第一个目标
                enableRouteSearchBox: true,
                enableRouteInfo:true
            },
            pageCapacity: 1
        });

        local.setSearchCompleteCallback(function (searchResult) {
            var poi = searchResult.getPoi(0);
            //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
            map.centerAndZoom(poi.point, 12);
            gc.getLocation(poi.point, function(rs){
                showLocationInfo(poi.point, rs);
            });
        });
        local.search(_this);
    }
}

//搜索地址并赋值给form
$("#province,#city,#district").change(function(){
    $("#address").val("");
    deletePoint();
    _area.init();
});
//全局变量：存储address字符串长度做判断
var _thisLength='';
$("#address").keydown(function(){
    _thisLength=$(this).val().length;
})
$("#address").keyup(function(){
    var _newLength=$(this).val().length;
    var timer=setTimeout(function(){
        if(_thisLength<=_newLength){
            deletePoint();
            _area.init();
        }
        else{
            clearTimeout(timer);
        }
    },1000);
})
$("#address").blur(function(){
    deletePoint();
    _area.init();
})
//_area.init();


$(function() {
    roleManage.init();
});



//图片控件 --begin
var pic_table = $('#pic_table');
var  tagImg = $('.upPicCon .storeimg').find('input[name="tagImg"]').val();
if(tagImg.length !== 0) {
    imgcount = tagImg.split(',').length;
}
tagImg  += ',';
pic_table.dataTable({
    "processing": true,
    serverSide: false,
    destroy:false,
    "ajax": {
        url:layer_img,
    },
    "autoWidth": false,
    "columns": [
        {
            "width": "10%",
            "data": "imgUrl",
            "render": function(data, type, row, meta) {
                if(tagImg.indexOf(row.id+',') !== -1) {
                    return '<div class="left image"><label for="" class="active"><img class="select" src="/public/static/admin/pages/image/yes.png"></label>'+
                        '<div style="display: none;"><input type="checkbox" name="imageId" checked value="'+row.id+'"><input type="checkbox" checked name="imageUrl" value="'+data+'"></div>'+
                        '<img class="upPicList" src="'+data+'" /></div>';
                } else {
                    return '<div class="left image"><label for="" class="active" style="display: none"><img class="select" src="/public/static/admin/pages/image/yes.png"></label>'+
                        '<div style="display: none;"><input type="checkbox" name="imageId" value="'+row.id+'"><input type="checkbox" name="imageUrl" value="'+data+'"></div>'+
                        '<img class="upPicList" src="'+data+'" /></div>';
                }
            }
        },
    ],
    "language": {
        url: '/public/static/assets/pages/Chinese.json'
    },
    "pageLength": 18,
    "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
    "<t>" +
    "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
    "fnInitComplete": function() {}
});

pic_table.on('click', '.upPicList', function(event) {
    $(this).parent().find(".active").toggle();
    console.log('原始' + imgcount);
    var id = $(this).parent().find("input[name='imageId']").val();   //图片id
    var url = $(this).attr('src');   //图片地址

    var img = new Image();
    img.src = url;
    if(img.width < 750 || img.height < 560) {
        layer.msg('图片尺寸不合理，请重新选择');
        $(this).parent().find(".active").toggle();
        $(this).parent().find("input").prop("checked", false);
        return;
    }

    if ($(this).parent().find(".active").is(':visible')) {  //选中,添加
        if (imgcount >= 9) {
            layer.msg('最多添加9张图片');
            $(this).parent().find('.active').hide();
            return;
        }
        imgcount++;
        console.log('增加' + imgcount);
        $(this).parent().find("input").prop("checked", true);
        var $item = ($('<div class="left"><div style="display: none;"><input type="checkbox" name="imageId" checked value="'+id+'"><input type="checkbox" checked name="imageUrl" value="'+url+'"></div><img class="btn-del" src="/public/static/admin/pages/image/del.png" alt="" onclick="deleteIndex(this)"><img class="upPic" src="' + url + '" name="img" style="width: 150px;height: 112px;"/></div>'));
        $('.uploaderCon').before($item);

    } else {
        if (imgcount <= 1) {
            layer.msg('最后一张图片，不能删除');
            $(this).parent().find('.active').show();
            return;
        }
        imgcount--;
        console.log('减少' + imgcount);
        $(this).parent().find("input").removeAttr("checked");
        $("#storeImg .left img[name='img']").each(function (i) {
            var imgsrc = $(this).attr('src');
            if(imgsrc.indexOf('?') > 0) {
                imgsrc = imgsrc.slice(0,imgsrc.indexOf('?'));
            }
            if (imgsrc == url) {  // 删除图片
                $(this).parent().remove();
            }
        });
    }
});

getTokenMessageForImg(pic_table);

//关闭弹窗前检查数量
$('#uploaderBox .close-check').click(function(){
    if(imgcount > 9) {
        layer.msg('最多添加9张图片，请去掉多余图片');
        return false;
    } else {
        $('.modal').hide();
    }
});
//图片控件 --end 

//图片删除
function deleteIndex(e) {  //删除已选中图片
    if(imgcount <= 1) {  //检测图片数量
        layer.msg('最后一张图片，不能删除');
        return;
    }
    if($(e).parent().find('input[name="imgId"]').is(':checked')) {  //检测是否为主图，若是，不允许删除
        layer.msg('主图不能被删除，若想删除，请选择其他图片为主图');
        return;
    }
    imgcount--;

    var id = $(e).parent().find('input[name="imageId"]').val();
    var nTrs=$('#pic_table').dataTable().fnGetNodes();  //表格中所有页中的项
    for(var i = 0; i < nTrs.length; i++){
       if($(nTrs[i]).find('input[name="imageId"]').val() == id){  //去除图片组件中的选中样式
            $(nTrs[i]).find('input[name="imageId"]').removeAttr('checked');
            $(nTrs[i]).find('input[name="imageUrl"]').removeAttr('checked');
            $(nTrs[i]).find('label.active').hide();
        }
   }
    $(e).parent().remove();  //删除页面显示元素

}


function getTokenMessageForImg(pic_table) {
    var url="";
    var qiniupercent="";
    var uploader="already";
    var pickfiles="localUp";
    $.ajax({
        url: token_url,
        type: 'POST',
        data: {},
        cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
        dataType : 'json',
        success: function (data) {
            var obj = data;
            uploaderReadyForImg(obj.uptoken,url,qiniupercent,uploader,pickfiles,pic_table);
        }
    });
};

function uploaderReadyForImg(token,url,qiniupercent,uploader,pickfiles,pic_table){
    var uploaderForUditor = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: pickfiles,     //上传按钮的ID
        container: uploader,      //上传按钮的上级元素ID
        drop_element: uploader,
        max_file_size: '1mb',         //最大文件限制
        flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
        dragdrop: false,
        chunk_size: '4mb',              //分块大小
        //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
        uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
        domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
        multi_selection: true,         //是否允许同时选择多文件
        filters: {
            mime_types: [               //文件类型过滤，这里限制为图片类型
                {title: "Image files", extensions: "jpg,jpeg,gif,png"}
            ]
        },
        auto_start: true,
        unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
        init: {
            'FilesAdded': function (up, files) {
                plupload.each(files, function (file) {
                    // 文件添加进队列后，处理相关的事情
                    var nativeFile = file.getNative();
                    var img = new Image();
                    img.src = URL.createObjectURL(nativeFile);
                    img.onload = function() {
                        var width = img.naturalWidth;
                        var height = img.naturalHeight;
                        if(width < 750 || height < 560) {
                            layer.msg('图片分辨率不足750*560，请重新上传');
                            up.removeFile(file);
                            return;
                        } else {
                            // img.src = URL.createObjectURL(nativeFile);
                            // up.start();
                        }
                    }
                });
            },
            'BeforeUpload': function (up, file) {
                // 每个文件上传前，处理相关的事情
            },
            'UploadProgress': function (up, file) {
                //文件上传时，处理相关的事情

                /*可能是文件大小
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                */

                //上传进度 class="layui-btn" type="button"
                // $('#'+qiniupercent).attr('style','width:'+file.percent+'%');
                // $("#"+qiniupercent).css("background-color","green");

                //console.log(file.percent + "%");
            },
            'UploadComplete': function () {
                //do something
            },
            'FileUploaded': function (up, file, info) {
                //每个文件上传成功后,处理相关的事情,并记录到数据库
                //其中 info 是文件上传成功后，服务端返回的json，形式如
                //{
                //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //  "key": "gogopher.jpg"
                //}
                var domain = up.getOption('domain');
                var res = eval('(' + info.response + ')');
                var sourceLink = domain + res.key;//获取上传文件的链接地址


                $.ajax({
                    url: record_url,
                    type: 'POST',
                    data: {
                        'imgUrl': sourceLink,
                        'controller': 'store'
                    },
                    cache: false,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code === '1') {
                            var $item = ($('<div class="left"><div style="display: none;"><input type="checkbox" name="imageId" checked value="'+data.image_id+'"><input type="checkbox" checked name="imageUrl" value="'+sourceLink+'"></div><img class="btn-del" src="/public/static/admin/pages/image/del.png" alt="" onclick="deleteIndex(this)"><img class="upPic" src="' + sourceLink + '" name="img" style="width: 150px;height: 112px;"/></div>'));
                            $('.uploaderCon').before($item);
                            tagImg = tagImg + data.image_id + ',';
                            pic_table.DataTable().ajax.reload();
                            imgcount++;

                        }
                    }
                });

            },
            'Error': function (up, err, errTip) {
                layer.msg(errTip);
            },
        }
    });
    // uploaderForUditor.start(); 
}

function beback(){
    window.location.href = index_url;
}